package com.chain.qs.modules.biz.service;

import com.chain.qs.common.service.CrudService;
import com.chain.qs.common.utils.CacheUtils;
import com.chain.qs.common.utils.EhCacheUtils;
import com.chain.qs.common.utils.TimeUtils;
import com.chain.qs.modules.biz.dao.HandoverInfoDao;
import com.chain.qs.modules.biz.entity.Handover;
import com.chain.qs.modules.biz.entity.HandoverException;
import com.chain.qs.modules.biz.entity.HandoverInfo;
import com.chain.qs.modules.biz.entity.HandoverView;
import com.chain.qs.modules.sys.entity.User;
import com.chain.qs.modules.sys.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 交接班流水Service
 *
 * @author wangzhiping
 */
@Service
//@Transactional(readOnly = true)
public class HandoverInfoService extends CrudService<HandoverInfoDao, HandoverInfo> {
    @Resource
    private HandoverService handoverService;

    @Resource
    private HandoverExceptionService handoverExceptionService;

    public HandoverInfo getLastInfo(User user) {
        return dao.getLastInfo(user);
    }

    public HandoverInfo getTodayHandoverInfo() {
        return dao.getTodayHandoverInfo();
    }

    /**
     * @return
     * @ param type
     */
    public Map getCurClass() {
        Handover handover = handoverService.getHandover();
        Date date = new Date();
        Map classMap = new HashMap();
        classMap.put("name", "无班次");
        classMap.put("startTime", "");
        classMap.put("endTime", "");
        classMap.put("bufferTime", handover.getBufferTime());
        if (isBetween(date, handover.getStime1(), handover.getEtime1())) {
            classMap.put("id", "1");
            classMap.put("name", handover.getName1());
            classMap.put("startTime", getTime(handover.getStime1()));
            classMap.put("endTime", getTime(handover.getEtime1()));
        } else if (isBetween(date, handover.getStime2(), handover.getEtime2())) {
            classMap.put("id", "2");
            classMap.put("name", handover.getName2());
            classMap.put("startTime", getTime(handover.getStime2()));
            classMap.put("endTime", getTime(handover.getEtime2()));
        } else if (isBetween(date, handover.getStime3(), handover.getEtime3())) {
            classMap.put("id", "3");
            classMap.put("name", handover.getName3());
            classMap.put("startTime", getTime(handover.getStime3()));
            classMap.put("endTime", getTime(handover.getEtime3()));
        }
        return classMap;
    }

    private boolean isBetween(Date date, String startTime, String endTtime) {
        String time = getTime(date);
        if (endTtime.compareTo(startTime) > 0) {   //结束时间大于开始时间   没有跨日
            if (time.compareTo(startTime) > 0 && endTtime.compareTo(time) > 0) {
                return true;
            }
        } else {
            //结束时间小于  过了12点
            if (startTime.compareTo(time) < 0 && endTtime.compareTo(time) < 0) { //   0点前
                return true;
            } else if (startTime.compareTo(time) > 0 && endTtime.compareTo(time) > 0) {  //0点后
                return true;
            }
        }
        return false;
    }

    private boolean isBetween(Date date, Date date1, Date date2) {
        String time1 = getTime(date1);
        String time2 = getTime(date2);
        return isBetween(date, time1, time2);
    }

    private String getTime(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        String tmp = "";
        try {
            tmp = df.format(date);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return tmp;
    }

    public boolean checkTime() {
        Map curClass = getCurClass();
        TimeUtils bufferTime = new TimeUtils(0, getInteger(curClass.get("bufferTime")), 0);

        TimeUtils startTime = new TimeUtils(curClass.get("startTime").toString());//当前班次上班时间缓冲区间
        TimeUtils startTimeBegin = startTime.subtractTime(bufferTime);//上班时间区间  开始时间点
        TimeUtils startTimeEnd = startTime.addTime(bufferTime);//上班时间区间  结束时间点

        TimeUtils endTime = new TimeUtils(curClass.get("endTime").toString());//当前班次下班时间
        TimeUtils endTimeBegin = endTime.subtractTime(bufferTime);
        TimeUtils endTimeEnd = endTime.addTime(bufferTime);

        if (isBetween(new Date(), endTimeBegin.toTimeString(), endTimeEnd.toTimeString())) {
            //当前班次结束交接班时间段内
            return true;
        } else if (isBetween(new Date(), startTimeBegin.toTimeString(), startTimeEnd.toTimeString())) {
            //当前班次开工缓冲时间段内
            return true;
        }
        return false;
    }

    private int getInteger(Object bufferTime) {
        if (bufferTime != null & (bufferTime instanceof Integer || bufferTime instanceof String)) {
            return Integer.parseInt(bufferTime.toString());
        }
        return 0;
    }
/*
检查换班时间内的换班次数
 */
    public int handoverTimes() {
        Map curClass = getCurClass();
        TimeUtils bufferTime = new TimeUtils(0, getInteger(curClass.get("bufferTime")), 0);

        TimeUtils startTime = new TimeUtils(curClass.get("startTime").toString());//当前班次上班时间缓冲区间
        TimeUtils startTimeBegin = startTime.subtractTime(bufferTime);//上班时间区间  开始时间点
        TimeUtils startTimeEnd = startTime.addTime(bufferTime);//上班时间区间  结束时间点

        TimeUtils endTime = new TimeUtils(curClass.get("endTime").toString());//当前班次下班时间
        TimeUtils endTimeBegin = endTime.subtractTime(bufferTime);
        TimeUtils endTimeEnd = endTime.addTime(bufferTime);

        int times = 0;
        HandoverInfo [] handoverInfo = dao.getNearbyHandoverInfo();
        for(HandoverInfo index:handoverInfo){
           if(isBetween(index.getDate(), endTimeBegin.toTimeString(), endTimeEnd.toTimeString())){
               times++;
           }if (isBetween(index.getDate(), startTimeBegin.toTimeString(), startTimeEnd.toTimeString())) {
                times++;
            }
        }
        return times;
    }

    public Map save(HandoverInfo handoverInfo, HttpServletRequest request) {
        handoverInfo.setFlag(0);

        String password = request.getParameter("password");
        String successorId = request.getParameter("successor.id"); //接班人编号
        String exception = request.getParameter("exceptionType");
        String providerId = request.getParameter("provider.id"); //交班人编号
        Map result = new HashMap();

        User olduser = null;
        if (providerId != null && !"".equals(providerId)) {
            olduser = UserUtils.get(providerId);
        } else {
//            SystemAuthorizingRealm.Principal principal = getPrincipal();
//            if (principal != null) {
//            }
            olduser = new User();

        }

        //TODO 验证接班人帐户
        User successorUser = new User();
//        successorUser.setLoginName(successorId);
        successorUser.setId(successorId);
        successorUser.setPassword(password);
        boolean vUser = UserUtils.changeUser(successorUser, request);
        if (!vUser) {
            //用户验证失败
            result.put("success", false);
            result.put("message", "'用户密码错误！'");
        } else {
            if (exception != null && exception!="null") {
                handoverInfo.setFlag(1);

                HandoverException handoverException = new HandoverException();
                handoverException.setDate(new Date());

                handoverException.setSuccessor(successorUser);
                if ("option1".equals(exception)) {
                    handoverException.setExceptionReason("提前交接班");
                } else if ("option2".equals(exception)) {
                    handoverException.setExceptionReason("接班人迟到");
                } else if ("option3".equals(exception)) {
                    handoverException.setExceptionReason("无交班人，顶班操作！");
                }

                if (olduser != null) {
                    handoverException.setProvider(olduser);
                }

                handoverException.setFlag(0);
                handoverExceptionService.save(handoverException);
                handoverInfo.setException(handoverException);
            }
            else if(handoverTimes()>0){
                handoverInfo.setFlag(1);

                HandoverException handoverException = new HandoverException();
                handoverException.setDate(new Date());
                handoverException.setSuccessor(successorUser);
                handoverException.setExceptionReason("交班时间内多次换班！");
                if (olduser != null) {
                    handoverException.setProvider(olduser);
                }

                handoverException.setFlag(0);
                handoverExceptionService.save(handoverException);
                handoverInfo.setException(handoverException);
            }
            handoverInfo.setDate(new Date());
            //获取当前班次
            Map curClass = getCurClass();

            HandoverView handoverView = new HandoverView();
            handoverView.setId(curClass.get("id").toString());
            handoverView.setName(curClass.get("name").toString());
            handoverInfo.setProvider(olduser);
            successorUser.setName(UserUtils.get(successorId).getName());
            handoverInfo.setSuccessor(successorUser);
            handoverInfo.setHandoverView(handoverView);
            save(handoverInfo);
            //设置缓存中的状态
            EhCacheUtils.put(EhCacheUtils.HANDOVER_CACHE, curClass.get("name").toString(), 1);
            CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_HANDOVER);
            CacheUtils.put(UserUtils.USER_CACHE, UserUtils.USER_CACHE_HANDOVER, handoverInfo);

            result.put("success", true);
            result.put("message", "'交接班成功！'");
        }
        return result;
    }

}
